package com.zxhtom.application;

import com.alibaba.fastjson.JSONObject;
import com.github.zxhTom.csdnSdk.handler.Blog;
import com.github.zxhTom.csdnSdk.model.Article;
import com.github.zxhTom.csdnSdk.model.Result;
import com.github.zxhTom.csdnSdk.utils.TokenUtil;
import com.qiniu.http.Response;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.zxhtom.service.TransformOffice;
import org.zxhtom.utils.FileUtil;
import org.zxhtom.utils.HttpClientUtil;
import org.zxhtom.utils.MarkdownUtil;
import org.zxhtom.utils.RegexUtil;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Hello {
    private static Logger logger = LogManager.getLogger(Hello.class);

    static {
        JSONObject jSONObject = TokenUtil.getInstance().login("*", "*");
    }


    private static void initMarkDown(String path) {
        initMarkDown(path, false);
    }


    private static void initMarkDown(String path, boolean trans) {
        Blog blog = new Blog();
        Result articleList = blog.getArticleList();
        Map<String, String> titleMap = new HashMap<String, String>();
        if (articleList.getCode() == 1) {
            List<Article> list = (List) articleList.getData();
            for (Article article : list) {
                titleMap.put(article.getTitle(), "https:" + article.getUrl());
            }
        }
        String preQny = "http://oytmxyuek.bkt.clouddn.com/";
        ArrayList<String> files = getFiles(path);
        for (String file : files) {

            if (!Pattern.matches(".*\\.md", file)) {
                continue;
            }
            for (int i = 0; i < 1000; i++) {
                if (i == 0) {
                    logger.info("rest");
                }
                if (i == 999) {
                    logger.info("end");
                }
            }
            logger.info(file);
            String fileName = "lqj";
            try {
                File realFile = new File(file);
                List<Map<String, String>> list = FileUtil.getInstance().getLocalFilePathByFolderAndContent(path, FileUtil.getInstance().readStrFromFile(realFile));
                Map<String, Object> mdap = MarkdownUtil.getInstance().getItemFromMDCommon(FileUtil.getInstance().readLineStrFromFile(realFile));
                String filePreName = getSortByType(mdap.get("date").toString(), "yyyyMMdd");
                rollbackFile(realFile,filePreName,list,mdap);
                logger.info("本地图片:" + list.size());
                for (int i = 0; i < list.size(); i++) {
                    Map<String, String> map = (Map) list.get(i);
                    String referer = (titleMap.get(mdap.get("title").toString().trim()) == null) ? "" : ((String) titleMap.get(mdap.get("title").toString().trim())).toString();
                    localHandler(preQny, filePreName, file, map);
                    networkHandler(path + "//photo//" + mdap.get("title").toString().trim(), preQny, filePreName, file, map, referer);
                }

                if (!trans) {
                    continue;
                }
                String prefix = "";
                if (mdap.containsKey("prefix")) {
                    prefix = mdap.get("prefix").toString();
                }
                if (StringUtils.isEmpty(prefix) || RegexUtil.getInstance().isContainChinese(prefix).booleanValue()) {
                    prefix = "zxh";
                }
                prefix = realFile.getParentFile().getParentFile().getAbsolutePath() + "//" + prefix + "//" + mdap.get("title").toString().replace(" ", "") + ".md";
                FileUtil.getInstance().copyFile(realFile.getAbsolutePath().toString(), prefix);
                realFile.delete();
                Set<String> parentFile = new HashSet<>();
                //图片删除
                for (Map<String, String> map : list) {
                    String absolute = map.get("absolute");
                    System.out.println("@@"+absolute);
                    File absoluteFile = new File(absolute);
                    String parent = absoluteFile.getParent();
                    parentFile.add(parent);
                }
                for (String s : parentFile) {
                    File pfile = new File(s);
                    if (pfile.listFiles().length == 0) {
                        pfile.delete();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将文章打包值back文件夹下备份
     * @param realFile
     */
    public static void rollbackFile(File realFile,String dateName , List<Map<String, String>> list,Map<String, Object> mdap) throws InterruptedException {
        String filePath = realFile.getAbsolutePath().toString();
        String rollbackFolder = realFile.getParent() + "/back/" + dateName;
        String newPath = rollbackFolder +"/"+realFile.getName();
        FileUtil.getInstance().copyFile(filePath,newPath);
        //存储图片
        List<Map<String, String>> newList = FileUtil.getInstance().getLocalFilePathByFolderAndContent(newPath, FileUtil.getInstance().readStrFromFile(realFile));
        Map<String,Object> map = imgListToMap(list);
        Map<String,Object> newMap = imgListToMap(newList);
        newMap.forEach((key,value)->{
            FileUtil.getInstance().copyFile(map.get(key).toString(), value.toString());
        });
        for (Map<String, String> temMap : list) {
            if (temMap.containsKey("network")) {
                String network = temMap.get("network");
                String abPath = rollbackFolder+"/"+mdap.getOrDefault("prefix","zxhtom").toString()+"/"+getNetWorkFileName(network);
                if (abPath.indexOf(".") == -1) {
                    abPath = abPath + ".png";
                }
                String abName = new File(abPath).getName();
                HttpClientUtil.getInstance().download(network, abPath, new HttpClientUtil.HttpClientDownLoadProgress() {

                    @Override
                    public void onProgress(int progress) {
                        System.out.println("download progress = " + progress);
                    }

                    @Override
                    public void onSuccess() throws IOException {
                        FileUtil.getInstance().replaceTextContent(newPath, network, "./"+mdap.get("prefix").toString()+"/"+abName);
                    }
                }, null);
                //为了等待下载，这里写死
                Thread.sleep(1000*5);
            }
        }
        FileUtil.getInstance().toZip(rollbackFolder,"zxhtom");
    }

    /**
     * 将图片按相对路径:绝对路径存储
     * @param list
     * @return
     */
    private static Map<String, Object> imgListToMap(List<Map<String, String>> list) {
        Map<String, Object> map = new HashMap<>();
        for (Map<String, String> temMap : list) {
            if (temMap.containsKey("relative")) {
                map.put(temMap.get("relative"), temMap.get("absolute"));
            }
        }
        return map;
    }


    private static String getFilePreName(String file) {
        String regex = "\\-{3}" + System.lineSeparator() + "(.*" + System.lineSeparator() + "*)*\\-{3}";
        String result = FileUtil.getInstance().readLineStrFromFile(new File(file));
        Matcher matcher = Pattern.compile(regex).matcher(result);

        while (matcher.find()) {
            for (int i = 0; i < matcher.groupCount(); i++) {
                String group = matcher.group(i);

                Matcher matcher1 = Pattern.compile("date: (.*)").matcher(group);
                if (matcher1.find()) {
                    return matcher1.group(1);
                }
            }
        }
        return null;
    }

    private static String getSortByType(String dateStr, String format) {
        if (StringUtils.isNotEmpty(dateStr)) {
            String seperator = dateStr.substring(5, 6);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy" + seperator + "MM" + seperator + "dd hh:mm:ss");
            SimpleDateFormat resultSdf = new SimpleDateFormat(format);
            return dateStr.substring(0, 4) + dateStr.substring(5, 7) + dateStr.substring(8, 10);
        }
        return "";
    }


    private static void networkHandler(String path, String preQny, String filePreName, String file, Map<String, String> map, String referer) {
        if (!map.containsKey("network")) {
            return;
        }

        try {
            String network = (String) map.get("network");
            if (network.indexOf("?") != -1) {
                network = network.substring(0, network.indexOf("?"));
            }
            if (Pattern.matches("http:\\/\\/oytmxyuek.bkt.clouddn.com\\/.*", network)) {
                return;
            }
            String abPath = path + "//" + getNetWorkFileName(network);
            if (abPath.indexOf(".") == -1) {
                abPath = abPath + ".png";
            }
            String key = filePreName + getNetWorkFileName(abPath);
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("referer", referer);

            final String tabPath = abPath;
            final String tkey = key;
            final String tfile = file;
            final String tnetwork = network;
            final String tpreQny = preQny;

            HttpClientUtil.getInstance().download(network, abPath, new HttpClientUtil.HttpClientDownLoadProgress() {

                @Override
                public void onProgress(int progress) {
                    System.out.println("download progress = " + progress);
                }

                @Override
                public void onSuccess() throws IOException {
                    Response response = (new QiNiuFileUpUtil()).upload(tabPath, tkey);
                    if (response != null && response.statusCode == 200) {
                        FileUtil.getInstance().replaceTextContent(tfile, tnetwork, tpreQny + tkey);
                    }
                }
            }, headMap);
        } catch (Exception e) {
            System.out.println("error:" + e);
        }
    }


    private static void localHandler(String preQny, String filePreName, String file, Map<String, String> map) throws IOException {
        if (!map.containsKey("absolute") || !map.containsKey("relative")) {
            return;
        }
        String abPath = (String) map.get("absolute");

        String key = filePreName + getFileName(abPath) + abPath.substring(abPath.lastIndexOf("."));
        Response response = (new QiNiuFileUpUtil()).upload(abPath, key);
        if (response != null && response.statusCode == 200) {
            FileUtil.getInstance().replaceTextContent(file, (String) map.get("relative"), preQny + key);
            logger.info("trans complete！please public blog");
        }
    }


    public static void transForm(String source) {
        String target = "E://zxh//test//tew.pdf";
        TransformOffice trans = new TransformOffice();

        File pptFile = new File(source + "//ppt");
        File docFile = new File(source + "//doc");
        if (!pptFile.exists()) {
            pptFile.mkdirs();
        }
        if (!docFile.exists()) {
            docFile.mkdirs();
        }
        ArrayList<String> files = getFiles(source);
        for (String file : files) {
            String fileName = "lqj";
            fileName = getFileName(file);
            String pathName = source;
            if (file.indexOf(".ppt") != -1) {
                pathName = pathName + "//ppt//" + fileName;
            } else if (file.indexOf(".doc") != -1) {
                pathName = pathName + "//doc//" + fileName;
            } else {
                continue;
            }
            trans.doTransform(file, pathName + ".pdf");
        }
        System.out.println("complete");
    }

    public static String getFileName(String filePath) {
        String reg = "([^<>/\\\\|:\"\"\\*\\?]+)\\.\\w+$+";
        Matcher m = Pattern.compile(reg).matcher(filePath);
        String filename = null;
        if (m.find()) {
            filename = m.group(1);
        }
        return filename;
    }

    public static String getNetWorkFileName(String filePath) {
        String reg = "([^<>/\\\\|:\"\"\\*\\?]+)$+";
        Matcher m = Pattern.compile(reg).matcher(filePath);
        String filename = null;
        if (m.find()) {
            filename = m.group(1);
        }
        return filename;
    }

    @SuppressFBWarnings({"NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE"})
    public static ArrayList<String> getFiles(String path) {
        ArrayList<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();
        if (tempList != null) {
            for (int i = 0; i < tempList.length; i++) {
                if (tempList[i].isFile()) {
                    files.add(tempList[i].toString());
                }
                if (tempList[i].isDirectory()) {
                    files.addAll(getFiles(tempList[i].getPath()));
                }
            }
        }
        if (file.isFile()) {
            files.add(file.toString());
        }
        return files;
    }

    public void test() {
        System.out.println(getClass().getResource(""));
    }

    @SuppressFBWarnings({"SF_SWITCH_NO_DEFAULT"})
    public static void main(String[] args) throws ReflectiveOperationException, SecurityException {
        Hello hello = new Hello();
        hello.test();
        args = new String[]{"markdown","/media/root/OS/zxh/project/note/blog/source/_posts/args/mybatis精讲(四)--ObjectFactory.md","true"};
        String source = args[0];
        if (StringUtils.isNotEmpty(source)) {
            String str = source;
            switch (str) {
                case "office":
                    transForm(args[1]);
                    break;
                case "markdown":
                    if (args.length<3) {
                        initMarkDown(args[1]);
                        break;
                    }
                    initMarkDown(args[1], Boolean.parseBoolean(args[2]));
                    break;
                case "test":
                    FileUtil.getInstance().replaceTextContent("E:\\zxh\\md\\oracle������������(���).md", "http://oytmxyuek.bkt.clouddn.com", "���������zxhtompic");
                    break;
                case "csdn":
                    Csdn.ttt();
                    break;
            }
        }
    }
}
